<template>
  <div class="code-editor-container">
    <div class="editor-header">
      <el-select v-model="currentLanguage" class="language-select" placeholder="选择语言">
        <el-option :value="0" label="C" />
        <el-option :value="1" label="C++" />
        <el-option :value="3" label="Python" />
      </el-select>
    </div>
    
    <div ref="editorRef" class="editor-content"></div>
    
    <div class="editor-footer">
      <el-button 
        type="primary" 
        @click="handleSubmit" 
        :loading="isSubmitting"
        :disabled="!code.trim() || isSubmitting"
      >
        {{ isSubmitting ? '评测中...' : '提交代码' }}
      </el-button>
    </div>

    <!-- 结果展示 -->
    <div v-if="result" class="result-section">
      <code-result :result="result" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import CodeMirror from 'codemirror'
import CodeResult from './CodeResult.vue'
import codeApi from '@/api/code'
import type { SubmissionResult } from '@/api/code'

import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/dracula.css'
import 'codemirror/addon/scroll/simplescrollbars.css'
import 'codemirror/addon/scroll/simplescrollbars'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/anyword-hint'
import 'codemirror/mode/clike/clike'
import 'codemirror/mode/python/python'
import '../styles/code-editor.css'

const props = defineProps<{
  problemId: number
}>()

const emit = defineEmits(['submission-created'])

const editorRef = ref<HTMLElement | null>(null)
const editor = ref<CodeMirror.Editor | null>(null)
const currentLanguage = ref<number>(1)  // 默认 C++
const code = ref('')
const isSubmitting = ref(false)
const result = ref<SubmissionResult | null>(null)

// 获取语言对应的编辑器模式
const getModeByLanguage = (lang: number) => {
  switch (lang) {
    case 0:  // C
    case 1:  // C++
      return 'text/x-c++src'
    case 3:  // Python
      return 'text/x-python'
    default:
      return 'text/x-c++src'
  }
}

// 初始化编辑器
const initEditor = () => {
  if (!editorRef.value) return

  editor.value = CodeMirror(editorRef.value, {
    value: code.value,
    mode: getModeByLanguage(currentLanguage.value),
    theme: 'dracula',
    lineNumbers: true,
    indentUnit: 4,
    lineWrapping: true,
    tabSize: 4,
    autofocus: true,
    scrollbarStyle: 'simple',
    extraKeys: {
      'Ctrl-Space': 'autocomplete',
      'Tab': (cm) => {
        if (cm.somethingSelected()) {
          cm.indentSelection('add')
        } else {
          cm.replaceSelection('    ')
        }
      }
    }
  })

  editor.value.on('change', (cm) => {
    code.value = cm.getValue()
  })
}

// 提交代码
const handleSubmit = async () => {
  if (!code.value.trim()) {
    ElMessage.warning('请输入代码')
    return
  }

  if (!props.problemId) {
    ElMessage.error('题目ID不能为空')
    return
  }

  isSubmitting.value = true
  result.value = null

  try {
    // 提交代码
    const response = await codeApi.submitCode({
      problem: props.problemId,
      language: currentLanguage.value,
      code: code.value.trim()
    })

    // 如果提交成功，开始轮询结果
    if (response.code === 200) {
      const submission = response.data
      
      // 开始轮询获取结果
      const pollResult = async () => {
        try {
          const response = await codeApi.getSubmission(submission.id)
          if (response.code === 200) {
            const updatedSubmission = response.data
            
            // 如果还在评测中，继续轮询
            if (updatedSubmission.result <= 1) {  // 0-未提交, 1-等待评测
              setTimeout(pollResult, 1000)
            } else {
              result.value = updatedSubmission
              emit('submission-created', updatedSubmission)
              isSubmitting.value = false
            }
          } else {
            throw new Error(response.msg || '获取评测结果失败')
          }
        } catch (error: any) {
          console.error('Poll error:', error)
          ElMessage.error(error.message || '获取评测结果失败')
          isSubmitting.value = false
        }
      }

      pollResult()
    } else {
      throw new Error(response.msg || '提交失败')
    }
  } catch (error: any) {
    console.error('Submit error:', error)
    ElMessage.error(error.message || '提交失败')
    isSubmitting.value = false
  }
}

// 监听语言变化
watch(currentLanguage, (newLang) => {
  if (editor.value) {
    editor.value.setOption('mode', getModeByLanguage(newLang))
  }
})

onMounted(() => {
  initEditor()
})
</script>

<style scoped>
.code-editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #282a36;
  border-radius: 8px;
  overflow: hidden;
}

.editor-header {
  padding: 12px;
  background: #1e1f29;
  border-bottom: 1px solid #44475a;
}

.language-select {
  width: 120px;
}

.editor-content {
  flex: 1;
  overflow: hidden;
}

.editor-footer {
  padding: 12px;
  background: #1e1f29;
  border-top: 1px solid #44475a;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.result-section {
  margin-top: 20px;
  padding: 16px;
  background: #1e1f29;
  border-radius: 8px;
}

:deep(.el-select) {
  --el-select-border-color-hover: #bd93f9;
}

:deep(.el-input__wrapper) {
  background-color: #282a36;
  border-color: #44475a;
  box-shadow: none;
}

:deep(.el-input__wrapper:hover) {
  border-color: #bd93f9;
}

:deep(.el-button) {
  background-color: #bd93f9;
  border-color: #bd93f9;
}

:deep(.el-button:hover) {
  background-color: #9580c7;
  border-color: #9580c7;
}

:deep(.el-button:active) {
  background-color: #7b68a7;
  border-color: #7b68a7;
}

:deep(.el-button.is-disabled) {
  background-color: #44475a;
  border-color: #44475a;
  color: #6272a4;
}
</style>
